<template>
    <div>
        <div style="margin-bottom: 5px;">
            <el-input v-model="id" placeholder="请输入服务单号" suffix-icon="el-icon-search" style="width: 200px;"
                        @keyup.enter.native="loadPost"></el-input>
            <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button> 
        </div>
        <el-table :data="tableData"
                  :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
                  border
        >
            <el-table-column fixed prop="id" label="服务单号" width="70" align="center">
            </el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180" :formatter="formatTime" align="center">
            </el-table-column>
            <el-table-column prop="memberUsername" label="用户账号" align="center">
            </el-table-column>
            <el-table-column prop="returnAmount" label="退款金额" :formatter="formatReturnAmount" align="center">
            </el-table-column>
            <el-table-column prop="status" label="申请状态" align="center" :formatter="formatStatus">
            </el-table-column>
            <el-table-column prop="handleTime" label="处理时间" :formatter="formatTime1" align="center">
              <template slot-scope="scope">
                <!-- 判断处理时间是否为空 -->
                <div v-if="scope.row.handleTime === null || scope.row.handleTime === ''">
                  <!-- 如果处理时间为空，显示处理订单的按钮 -->
                  <el-button size="small"  @click="handleOrder(scope.row)">处理申请</el-button>
                </div>
                <div v-else>
                  <!-- 如果处理时间不为空，显示处理时间 -->
                  <span>{{ formatTime1(scope.row) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" prop="operate" label="操作" align="center">
                <template slot-scope="scope">
                    <!-- <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button> -->
                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="del(scope.row.id)"
                            style="margin-left: 5px;"
                    >
                        <el-button slot="reference" size="small" type="danger" >删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
        <el-dialog
            title="订单详情"
            :visible.sync="dialogVisible"
            width="50%"
            v-if="currentOrder !== null">
          <el-descriptions border  title="" :column="1" size="mini">
            <el-descriptions-item label="服务单号">{{ currentOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatTime(currentOrder) }}</el-descriptions-item>
            <el-descriptions-item label="用户账号">{{ currentOrder.memberUsername }}</el-descriptions-item>
            <el-descriptions-item label="退款金额">{{ formatReturnAmount(currentOrder) }}</el-descriptions-item>
            <el-descriptions-item label="退货原因">{{ currentOrder.reason }}</el-descriptions-item>
            <el-descriptions-item v-if="currentOrder.description !== null" label="详细描述">{{ currentOrder.description }}</el-descriptions-item>
            <el-descriptions-item label="申请状态">{{ formatStatus(currentOrder) }}</el-descriptions-item>
          </el-descriptions>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="agree">同意处理</el-button>
            <el-button type="danger" @click="disagree">拒绝处理</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
    import {formatDate} from '@/utils/date';
    import { mapState, mapActions } from 'vuex';
    export default {
        name:"OrderReturnApply",
        data(){
            return{
                tableData:[],
                id:'',
                pageSize:10,
                pageNum:1,
                total:0,
                dialogVisible: false, // 控制对话框的显示
                currentOrder: null, // 当前选中的订单信息
                now:'',
            }
        },
        methods:{
            ...mapActions(['fetchOrderSettings']),
            getTime(){
              if (this.$store.getters.getUserSelectedTime==null){
                this.now =  new Date();
              }else{
                this.now = this.$store.getters.getUserSelectedTime;
              }
            },
            formatReturnAmount(row){
                return row.productRealPrice*row.productCount;
            },
            // 计算时间差（秒）
            calculateTimeDifference(createTime) {
              const orderTime = new Date(createTime);
              const currentTime = this.now || new Date();
              return (currentTime - orderTime) / 1000; // 返回秒数
            },
            formatStatus(row){
                const timeDiff = this.calculateTimeDifference(row.handleTime)
                const finishOvertime = this.orderSetting.finishOvertime * 24 * 60 * 60
                const statusMap = {
                    0:'待处理',
                    1:'退货中',
                    2:'已完成',
                    3:'已拒绝',
                };
                console.log(JSON.stringify(row))
                if(row.status === 1 && timeDiff > finishOvertime)
                  row.status = 2
                return statusMap[row.status]
            },
            formatTime1(row){
                if(row.handleTime==null||row.handleTime===''){
                    return '申请还未处理';
                }
                let date = new Date(row.handleTime);
                return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
            },
            formatTime(row){
                if(row.createTime==null||row.createTime===''){
                    return 'null';
                }
                let date = new Date(row.createTime);
                return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
            },
            handleOrder(row){
              this.currentOrder = row; // 存储当前订单信息
              this.dialogVisible = true; // 显示对话框
            },
            agree(){
              this.dialogVisible = false; // 关闭对话框
              this.currentOrder.status = 1
              this.currentOrder.handleTime = this.now
              this.$axios.post(this.$httpUrl+'/orderReturnApply/update/'+this.currentOrder.id,this.currentOrder)
                .then(res=>res.data).then(res=>{
                  console.log(res)
              }).catch(error=>{
                console.log(error);
              });
            },
            disagree(){
              this.dialogVisible = false; // 关闭对话框
              this.currentOrder.status = 3
              this.currentOrder.handleTime = this.now
              this.$axios.post(this.$httpUrl+'/orderReturnApply/update/'+this.currentOrder.id,this.currentOrder)
                  .then(res=>res.data).then(res=>{
                console.log(res)
              }).catch(error=>{
                console.log(error);
              });
            },
            del(id){
                console.log(id)
                this.$axios.get(this.$httpUrl+'/orderReturnApply/del?id='+id).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){

                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.loadPost()
                    }else{
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                }).catch(error=>{
                  console.log(error);
                });
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum=1
                this.pageSize=val
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val
                this.loadPost()
            },
            loadPost(){
                this.$axios.post(this.$httpUrl+'/orderReturnApply/listPage',{
                    pageSize:this.pageSize,
                    pageNum:this.pageNum,
                    param:{
                        id:this.id
                    }
                }).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.tableData=res.data
                        this.total=res.total
                    }else{
                        alert('获取数据失败')
                    }
                })
            },
            resetParam(){
                this.id=''
            },
        },
        beforeMount() {
            this.loadPost()
            this.getTime()
        },
        computed:{
          ...mapState({
            orderSetting: state => state.orderSettings
          })
        }
    }
</script>
